//
//  TTCollectionViewController.m
//  TaoTuo
//
//  Created by 周晨晔 on 2019/9/20.
//  Copyright © 2019 admin. All rights reserved.
//

#import "TTCollectionViewController.h"
#import "TTHomeListTableViewCell.h"
#import "TTGoodsDetailViewController.h"

static NSString *cellID = @"colletcin_cellID";

@interface TTCollectionViewController ()<UITableViewDelegate, UITableViewDataSource, TTHomeListTableViewCellDelegate>

@property (nonatomic, assign) PageType pageType;

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, assign) NSInteger page;

@property (nonatomic, assign) NSInteger selectedIndex;  // 点击的那个cell

@end

@implementation TTCollectionViewController

- (instancetype)initWithPageType:(PageType)pageType
{
    self = [super init];
    if (self) {
        self.pageType = pageType;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = self.pageType == PageTypeWithTrack ? @"足迹" : @"收藏";
    self.page = 1;
    
    @weakify(self)
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        @strongify(self)
        self.page = 1;
        [self getNetworkData];
    }];
    
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        @strongify(self)
        self.page++;
        [self getNetworkData];
    }];
    
    
    [self getNetworkData];
    
    // 如果是收藏页面添加通知
    if (self.pageType == PageTypeWithCollection) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cancelCollectionNotify:) name:@"cancelORAddCollectionNotify_key" object:nil];
    }
    
}

// 取消收藏
- (void)cancelCollectionNotify:(NSNotification *)notify
{
    BOOL isCancel = [notify.object boolValue];
    if (isCancel) {
        [self.dataArray removeObjectAtIndex:self.selectedIndex];
        [self.tableView reloadData];
    } else {
        // 加入
        [self getNetworkData];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TTHomeListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    [cell setModel:self.dataArray[indexPath.row] pageType:self.pageType];
    cell.delegate = self;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.selectedIndex = indexPath.row;
    TTHomeListModel *model = self.dataArray[indexPath.row];
    TTGoodsDetailViewController *detailVC = [[TTGoodsDetailViewController alloc] initWithStyleLibraryId:model.StyleLibraryId model:nil];
//    detailVC.styleLibraryId = model.StyleLibraryId;
    [self.navigationController pushViewController:detailVC animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TTHomeListModel *model = self.dataArray[indexPath.row];
    
    NSArray *contentArray = model.DescriptionList;
    
    CGFloat h = ceil(contentArray.count / 2.0) * 22 + 94;
    h = h < 145 ? 145 : h;
    return h * kScale + 20;
}

- (void)getNetworkData
{
    NSDictionary *dic = @{
                          @"param.pageIndex" : @(self.page),
                          @"param.type" : @(self.pageType),
                          @"param.pageSize" : @(40)
                          };
    [[LLNetworkManagerTool sharedManager] requestMethod:GET urlString:getCollectionOrFootList_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (self.page == 1) {
            [self.dataArray removeAllObjects];
        }
        NSArray *arr = responseObject[@"Data"];
        for (NSDictionary *dic  in arr) {
            TTHomeListModel *model = [TTHomeListModel modelWithJSON:dic];
            [self.dataArray addObject:model];
        }
        
        [self.tableView.mj_header endRefreshing];
        if (arr.count < 40) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        } else {
            [self.tableView.mj_footer endRefreshing];
        }
        [self.tableView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        
    } showLoadingInView:self.tableView];
}

#pragma mark - TTHomeListViewCellDelegate
- (void)cancelCollectionBtnClickWithViewCell:(TTHomeListTableViewCell *)cell
{
    // 取消收藏
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    TTHomeListModel *model = self.dataArray[indexPath.row];
    NSDictionary *dic = @{
                          @"param.styleLibraryId" : model.StyleLibraryId
                          };
    [[LLNetworkManagerTool sharedManager] postUrlString:setCancelCollection_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [self.dataArray removeObject:model];
        [self.tableView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
    } showLoadingInView:self.view];
}

- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.tableFooterView = [UIView new];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.emptyImageName = @"nodata";
        _tableView.emptyTitel = @"暂无数据";
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[TTHomeListTableViewCell class] forCellReuseIdentifier:cellID];
        [self.view addSubview:_tableView];
        
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) { make.top.mas_equalTo(self.mas_topLayoutGuideTop);
            make.left.right.equalTo(self.view);
            make.bottom.equalTo(self.mas_bottomLayoutGuideBottom);
        }];
    }
    return _tableView;
}



- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
